package com.easychat.controller;

import com.easychat.annotation.GlobalInterceptor;
import com.easychat.entity.config.AppConfig;
import com.easychat.entity.constants.Constants;
import com.easychat.entity.dto.MessageSendDto;
import com.easychat.entity.dto.TokenUserInfoDto;
import com.easychat.entity.enums.MessageTypeEnum;
import com.easychat.entity.enums.ResponseCodeEnum;
import com.easychat.entity.po.ChatMessage;
import com.easychat.entity.vo.ResponseVO;
import com.easychat.exception.BusinessException;
import com.easychat.service.ChatMessageService;
import com.easychat.utils.SensitiveWordUtils;
import com.easychat.utils.StringTools;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Array;

/**
 * @Author Dongdong
 * @注释
 */

@RestController
@RequestMapping("/chat")
public class ChatController extends ABaseController {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(ChatController.class);

    @Resource
    private ChatMessageService chatMessageService;
    @Resource
    private AppConfig appConfig;

    @RequestMapping("/sendMessage")
    @GlobalInterceptor
    public ResponseVO sendMessage(HttpServletRequest request,
                                  @NotEmpty String contactId,
                                  @NotEmpty @Max(500) String messageContent,
                                  @NotNull Integer messageType,
                                  Long fileSize,
                                  String fileName,
                                  Integer fileType) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setContactId(contactId);
        //敏感词校验
        String filterMessage = SensitiveWordUtils.filter(messageContent);
        chatMessage.setMessageContent(filterMessage);

        chatMessage.setFileSize(fileSize);
        chatMessage.setFileName(fileName);
        chatMessage.setFileType(fileType);
        chatMessage.setMessageType(messageType);

        MessageSendDto messageSendDto = chatMessageService.saveMessage(chatMessage, tokenUserInfoDto);

        return getSuccessResponseVO(messageSendDto);
    }
    @RequestMapping("/uploadFile")
    @GlobalInterceptor
    public ResponseVO uploadFile(@NotNull Long messageId,
                                 @NotNull MultipartFile file,
                                 @NotNull MultipartFile cover,
                                 HttpServletRequest request){
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        chatMessageService.saveMessageFile(tokenUserInfo.getUserId(),messageId,file,cover);
        return getSuccessResponseVO(null);

    }

    /**
     * 下载图片
     * @param request
     * @param response
     * @param fileId  messageId
     * @param showCover  是否是封面图  拿封面图 还是原图
     */
    @RequestMapping("/downloadFile")
    @GlobalInterceptor
    public void downloadFile(HttpServletRequest request,
                             HttpServletResponse response,
                             @NotEmpty String fileId,
                             @NotNull Boolean showCover){
        TokenUserInfoDto tokenUserInfo = getTokenUserInfo(request);
        OutputStream out = null;
        FileInputStream in = null;
        try {
            File file = null;
            if (!StringTools.isNumber(fileId)){//如果不是数字，说明是头像
                String avatarFolderName = Constants.FILE_FOLDER_FILE+Constants.FILE_FOLDER_AVATAR_NAME;
//                D:/newNote/sourceCode/storeFile//file/avatar/U12486119627.png
                String avatarPath  =  appConfig.getProjectFolder()+avatarFolderName+fileId+Constants.IMAGE_SUFFIX;//G97086514045.png
                if (showCover){//如果是封面图
                    avatarPath  = avatarPath+Constants.COVER_IMAGE_SUFFIX;//G97086514045.png_cover.png
//                D:/newNote/sourceCode/storeFile//file/avatar/U12486119627.png_cover.png
                }
                file=new File(avatarPath);
                if (!file.exists()){
                    throw new BusinessException(ResponseCodeEnum.CODE_602);
                }
            }else {//聊天中的图片
                file = chatMessageService.downloadFile(tokenUserInfo, Long.parseLong(fileId), showCover);
            }
            //下载操作
            response.setContentType("application/x-msdownload; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;");
            response.setContentLengthLong(file.length());
            in = new FileInputStream(file);
            byte[] byteData = new byte[1024];
            out = response.getOutputStream();
            int len = 0;
            while ((len = in.read(byteData)) != -1) {
                out.write(byteData, 0, len);
            }
            out.flush();
        }catch (Exception e){
            logger.error("下载文件失败",e);
        }finally {
            //后创建的先关
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("IO异常", e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("IO异常", e);
                }
            }
        }
    }


}
